// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
    traceUser: true,
    env: 'aaa111-9gh9fp5ieac4de5d'
})

const db = cloud.database()
const $ = db.command.aggregate

// 云函数入口函数
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()
    var result = []
    //拿到空白清单
    var empty = await db.collection('checklist').aggregate()
    .group({
        _id:'$clas',
        countClas: $.sum(1)
    })
    .sort({
        _id: 1
    })
    .end()
    for (var i = 0 ;i < empty.list.length;i++){
        var clas = {}
        clas['name'] = empty.list[i]._id.slice(1)
        clas['amountAll'] = empty.list[i].countClas
        var clasContent = []
        var listDataTemp = []
        await db.collection('checklist').where({
            clas: empty.list[i]._id
        }).get().then(res => {
            console.log(res.data)
            listDataTemp = res.data
        })

        for(var j=0;j<listDataTemp.length;j++){
            var item = {}
            item["name"] = listDataTemp[j].name
            item["id"] = listDataTemp[j]._id
            await db.collection('userChecked').where({
                _openid: wxContext.OPENID,
                checklistid: listDataTemp[j]._id,
                tripid: event.tripid
            }).count().then(res => {
                console.log(res.total)
                if (res.total > 0) {
                    item["isdone"] = true
                } else {
                    item["isdone"] = false
                }
            })
            clasContent.push(item)
        }
        clas["clasContent"] = clasContent
        result.push(clas)
    }
    return result
}